import json
import re
import httpx
from typing import Any
import os
from dotenv import load_dotenv
load_dotenv()
# 汽车入厂API配置
CAR_QUERY = os.getenv("BASEA_CAR_URL", "") + "/prl-Vehicle/web/vEnterBackInfoVehicle/queryUnloadedVehicleInfo"
CAR_DECOAL = os.getenv("BASEA_CAR_URL", "")  + "/prl-Vehicle/web/vEnterBackInfoVehicle/saveBackInfoBatch"
CAR_COOKIE = os.getenv("FUEL_TOKEN", "")

async def decoal_car(vehicleNo: str, monitorPerson: str, backReason: str) -> str:
    params = {
        "vehicleNo": vehicleNo
    }
    headers = {
        "Content-Type": "application/json"
    }
    async with httpx.AsyncClient() as client:
        try:
            client.cookies.set('jreapSid', CAR_COOKIE)
            # 查询车牌号是否可以退煤
            response = await client.post(CAR_QUERY, json=params, headers=headers, timeout=30.0)
            response.raise_for_status()
            json_data = response.json()
            if json_data.get('flag') == 'error':
                return f"⚠️ {json_data['error']}"
            list = json_data.get('result')
            # 判断list的长度是否为0，如果为0，就返回{"error": "未找到车辆信息"}
            if len(list) == 0:
                return f"未找到车辆信息"
            first_element = list[0]
            # 获取first_element的serialNo和vehicleNo
            serialNo = first_element.get('serialNo')
            params = {
                "serialNoList": serialNo,
                "monitorPerson": monitorPerson,
                "backReason": backReason 
            }
            response_decol = await client.post(CAR_DECOAL, json=params, headers=headers, timeout=30.0)
            json_decol_data = response_decol.json()
            if json_decol_data.get('flag') == 'error':
                return f"⚠️ {json_decol_data['error']}"
            decol_result = json_decol_data.get('result')
            # 判断result为None返回退煤成功
            if decol_result is None:
                return "退煤成功"
            return decol_result
        except httpx.HTTPStatusError as e:
            return f"HTTP 错误: {e.response.status_code}"